package org.autojs.autojs.ampq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;

import org.autojs.autojs.autojs.AutoJs;

public class AmqpClient{

    private final String amqpUri;

    private final String queueName;

    private final String deviceExchange;

    private final String deviceRoutingKey;

    private Connection connection;

    private Channel channel;


    public AmqpClient(String amqpUri, String queueName, String deviceExchange, String deviceRoutingKey) {
        this.amqpUri = amqpUri;
        this.queueName = queueName;
        this.deviceExchange = deviceExchange;
        this.deviceRoutingKey = deviceRoutingKey;
    }

    public boolean conn(int connectionTimeout, int requestedHeartbeat, Consumer consumer) {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setUri(amqpUri);
            factory.setConnectionTimeout(connectionTimeout);
            factory.setRequestedHeartbeat(requestedHeartbeat);
            this.connection = factory.newConnection();
            this.channel = this.connection.createChannel();
            channel.queueDeclare(queueName, false, false, false, null);
            channel.queueBind(queueName, deviceExchange, deviceRoutingKey);
            channel.basicConsume(queueName, true, consumer);
            return true;
        } catch (Exception e) {
            AutoJs.getInstance().getGlobalConsole().log("创建连接失败:{}", e);
            close();
        }
        return false;
    }

    public void close() {
        AutoJs.getInstance().getGlobalConsole().log("关闭信道");
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (Exception e) {
            AutoJs.getInstance().getGlobalConsole().log("信道关闭失败:", e);
        }
        channel = null;
        AutoJs.getInstance().getGlobalConsole().log("关闭连接");
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            AutoJs.getInstance().getGlobalConsole().log("连接关闭失败:", e);
        }
        connection = null;
    }

}
